#include "connectAPI.h"

#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QUrl>
#include <QUrlQuery>
#include <QByteArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDebug>
#include <QProcessEnvironment>
#include <QLineEdit>
#include <QPushButton>
#include <QVBoxLayout>
#include <QTextEdit>
#include <QLabel>
#include <QFileDialog>
#include <QFile>
#include <QImageReader>
#include <QMimeDatabase>
#include <QMessageBox>

ContentWidget::ContentWidget(QWidget *parent)
    : QWidget(parent),
      conversationHistory(), // 初始化 conversationHistory
      selectedImagePath() // 初始化 selectedImagePath
{
    // 创建 UI 元素
    responseTextEdit = new QTextEdit("API返回的消息将显示在这里",this);
    responseTextEdit->setReadOnly(true); // 设置为只读，用于显示回复

    // 布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(responseTextEdit);

    setLayout(mainLayout);

    // 初始化对话历史，加入系统指令作为第一条消息
    QJsonObject systemInstructionObject;
    systemInstructionObject.insert("role", "user"); //  systemInstruction 也作为 user 的角色发送，Gemini API文档推荐这样做
    QJsonObject instructionPartObject;
    instructionPartObject.insert("text", "我是用户的私人棋盘助手，根据用户输入的3*3三子棋棋盘图片，按照我给的例子中的格式输出目前该棋盘布局，不得添加任何字符，例:XO中XOXOX中；若当前发送的图片棋盘布局与上一次图片棋盘布局相同，则输出‘非法操作’");
    QJsonArray instructionPartsArray;
    instructionPartsArray.append(instructionPartObject);
    systemInstructionObject.insert("parts", instructionPartsArray);
    conversationHistory.append(systemInstructionObject);
}

ContentWidget::~ContentWidget()
{
    // 手动删除 UI 元素 (虽然 Qt 的父子关系会自动管理，但显式删除更清晰)
    delete responseTextEdit;
}

void ContentWidget::on_sendButton_clicked()
{
    if (!selectedImagePath.isEmpty()) {
        // 将用户输入添加到对话历史
        QJsonObject userMessageObject;
        userMessageObject.insert("role", "user");
        QJsonArray userPartsArray;
        if (!selectedImagePath.isEmpty()) {
            QJsonObject imageData = processImage(selectedImagePath);
            if (!imageData.isEmpty()) {
                userPartsArray.append(imageData);
            } else {
                QMessageBox::warning(this, "Image Error", "Failed to process image.");
                return; // 如果图像处理失败，则不发送请求
            }
        }

        userMessageObject.insert("parts", userPartsArray);
        conversationHistory.append(userMessageObject);

        sendGeminiRequest(); // 修改为不直接传入 inputText，因为对话历史已经包含了
        selectedImagePath.clear(); // 清除图片路径
    }
}

void ContentWidget::on_uploadImageButton_clicked(const QString &fileName)
{
    FLAG_1_API_BACK_OK = 0;
    //此时清理返回值框
    responseTextEdit->clear();
    // 直接使用传入的 fileName
    if (!fileName.isEmpty()) {
        QFileInfo fileInfo(fileName);
         // 检查文件是否存在 (可选，根据需要添加)
        if (fileInfo.exists() && fileInfo.isFile())
        {
            selectedImagePath = fileName;
        }
        else
        {
             selectedImagePath = ""; // 清空路径
        }

    }
    else
    {
        // fileName 为空的处理 (可选)
        selectedImagePath = ""; //清空
    }
    on_sendButton_clicked();
}

QJsonObject ContentWidget::processImage(const QString& imagePath)
{
    QJsonObject imageData;
    QFile file(imagePath);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Failed to open image file:" << imagePath;
        return imageData; // 返回空对象表示失败
    }

    QByteArray imageDataBytes = file.readAll();
    QByteArray base64Image = imageDataBytes.toBase64();
    QString base64String = QString::fromUtf8(base64Image);

    QMimeDatabase mimeDb;
    QString mimeType = mimeDb.mimeTypeForFile(imagePath).name();
    if (mimeType.isEmpty()) {
        qDebug() << "Failed to determine MIME type for:" << imagePath;
        return imageData; // 返回空对象表示失败
    }

    imageData.insert("inline_data", QJsonObject({
        {"mime_type", mimeType},
        {"data", base64String}
    }));
    return imageData;
}

void ContentWidget::sendGeminiRequest() // 修改为不接受 inputText 参数
{
    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    QString apiKey = env.value("GOOGLE_API_KEY");

    if (apiKey.isEmpty()) {
        qDebug() << "Error: GOOGLE_API_KEY environment variable not set!";
        responseTextEdit->setText("Error: GOOGLE_API_KEY environment variable not set!");
        return;
    }

    QUrl url("https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-thinking-exp-01-21:generateContent");
    //QUrl url("https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-pro-exp-02-05:generateContent");
    QUrlQuery query;
    query.addQueryItem("key", apiKey);
    url.setQuery(query);

    QJsonObject requestData;

    // 构建 contents，包含整个对话历史
    QJsonArray contentsArray;
    for (const auto& message : conversationHistory) {
        contentsArray.append(message);
    }
    requestData.insert("contents", contentsArray);


    // 构建 generationConfig (保持不变)
    QJsonObject generationConfig;
    generationConfig.insert("temperature", 0.7);
    generationConfig.insert("topK", 64);
    generationConfig.insert("topP", 0.95);
    generationConfig.insert("maxOutputTokens", 65536);
    generationConfig.insert("responseMimeType", "text/plain");
    requestData.insert("generationConfig", generationConfig);

    QJsonDocument jsonDoc(requestData);
    QByteArray requestBody = jsonDoc.toJson();

    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    QNetworkAccessManager *manager = new QNetworkAccessManager(this);

    connect(manager, &QNetworkAccessManager::finished,
            this, [=](QNetworkReply *reply) {
        if (reply->error()) {
            qDebug() << "Error:" << reply->errorString();
            responseTextEdit->setText(QString("Error: ") + reply->errorString());
        } else {
            QByteArray responseData = reply->readAll();
            //qDebug() << "Response:" << responseData;

            QJsonDocument jsonResponse = QJsonDocument::fromJson(responseData);
            if (jsonResponse.isObject()) {
                QJsonObject responseObject = jsonResponse.object();
                if (responseObject.contains("candidates")) {
                    QJsonArray candidatesArray = responseObject["candidates"].toArray();
                    if (!candidatesArray.isEmpty()) {
                        QJsonObject candidateObject = candidatesArray[0].toObject();
                        if (candidateObject.contains("content")) {
                            QJsonObject contentObj = candidateObject["content"].toObject();
                            if (contentObj.contains("parts")) {
                                QJsonArray parts = contentObj["parts"].toArray();
                                if (!parts.isEmpty()) {
                                    QString responseText = "";
                                    foreach (const QJsonValue &partVal, parts) {
                                        if (partVal.isObject()) {
                                            QJsonObject partObj = partVal.toObject();
                                            if (partObj.contains("text")) {
                                                responseText += partObj["text"].toString();
                                            }
                                        }
                                    }

                                    //将回复显示在TextEdit
                                    responseTextEdit->setText(responseText);
                                    qDebug() << responseText;
                                    //判断回复是否合法
                                    if (responseText.length() == 9) {
                                        qDebug() << "The length of the text is 9.";
                                        //将数据交给棋盘处理
                                        Text = responseText;
                                        FLAG_1_API_BACK_OK = 1;
                                    } else {
                                        qDebug() << "The length of the text is not 9."<<responseText.length();
                                        FLAG_1_API_BACK_OK = 2;
                                        //直接返回
                                    }


                                    // 将模型的回复添加到对话历史
                                    QJsonObject modelMessageObject;
                                    modelMessageObject.insert("role", "model"); // 模型回复的角色是 "model"
                                    QJsonObject modelPartObject;
                                    modelPartObject.insert("text", responseText);
                                    QJsonArray modelPartsArray;
                                    modelPartsArray.append(modelPartObject);
                                    modelMessageObject.insert("parts", modelPartsArray);
                                    conversationHistory.append(modelMessageObject);

                                } else {
                                    responseTextEdit->setText("No response text found in parts.");
                                    qDebug() << "No response text found in parts.";
                                }
                            } else {
                                responseTextEdit->setText("No parts found in content.");
                                qDebug() << "No parts found in content.";
                            }
                        } else {
                            responseTextEdit->setText("No content found in candidate.");
                            qDebug() << "No content found in candidate.";
                        }
                    } else {
                        responseTextEdit->setText("No candidates found in response.");
                        qDebug() << "No candidates found in response.";
                    }
                } else if (responseObject.contains("error")) {
                    QJsonObject errorObject = responseObject["error"].toObject();
                    if (errorObject.contains("message")) {
                        responseTextEdit->setText(QString("API Error: ") + errorObject["message"].toString());
                        qDebug() << "API Error:" << errorObject["message"].toString();
                    } else {
                         responseTextEdit->setText("Unknown API Error.");
                         qDebug() << "Unknown API Error Response:" << responseData;
                    }
                } else {
                    responseTextEdit->setText("Unexpected response format.");
                    qDebug() << "Unexpected response format:" << responseData;
                }
            } else {
                responseTextEdit->setText("Invalid JSON response.");
                qDebug() << "Invalid JSON response:" << responseData;
            }
        }
        //提取纯文本对象responseTextEdit->toPlainText();
        reply->deleteLater();
        manager->deleteLater();
    });
    manager->post(request, requestBody);
}
